package com.lry.sso.auth.server.service.impl;

import com.lry.sso.auth.common.util.JWTHelper;
import com.lry.sso.auth.common.util.RsaKeyHelper;
import com.lry.sso.auth.common.util.SessionInfo;
import com.lry.sso.auth.server.bean.KeyConfiguration;
import com.lry.sso.auth.server.config.AuthConfigProperties;
import com.lry.sso.auth.server.service.JwtTokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 
 *
 * @author 李瑞益
 * @date 2019/9/5
 */
@Service
public class JwtTokenServiceImpl implements JwtTokenService {

    private static Logger logger = LoggerFactory.getLogger(JwtTokenServiceImpl.class);

    @Autowired
    private AuthConfigProperties authConfig;

    @Autowired
    private KeyConfiguration keyConfiguration;

    @Override
    public byte[] getUserPublicKey() {
        return keyConfiguration.getUserPubKey();
    }

    @Override
    public String getToken(SessionInfo sessionInfo) throws Exception {
        return JWTHelper.generateToken(sessionInfo, keyConfiguration.getUserPriKey(),authConfig.getJwtExpire());
    }

    @Override
    public String parsePassword(String password) throws Exception {
        return RsaKeyHelper.decrypt(password,keyConfiguration.getUserPriKey());
    }

    @Override
    public SessionInfo parseToken(String token) throws Exception {
        return JWTHelper.getInfoFromToken(token, keyConfiguration.getUserPubKey());
    }

    @Override
    public Long getExpire(String token) throws Exception {
        Jws<Claims> claimsJws = JWTHelper.parserToken(token, keyConfiguration.getUserPubKey());
        Object exp = claimsJws.getBody().get("exp");
        return Long.parseLong(exp.toString())*1000;
    }
}
